package com.code.family.utils;

import com.code.family.config.exception.UnauthorizedException;
import com.code.family.entity.annotation.CheckPermission;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 切面类
 * 用于检查用户是否有权限执行某个操作
 *
 * @author 上玄
 */
@Aspect
@Component
public class PermissionCheckAspect {

    public static String token;

    @Before("@annotation(checkPermission)")
    public void checkPermission(JoinPoint joinPoint, CheckPermission checkPermission) throws UnauthorizedException {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            // 获取注解中定义的权限名称
            String requiredPermission = checkPermission.value();
            // 执行权限校验逻辑
            if (!hasPermission(request, requiredPermission)) {
                throw new UnauthorizedException("用户没有权限执行该操作");
            }
        } catch (UnauthorizedException e) {
            throw new UnauthorizedException("用户没有权限执行该操作");
        }
    }

    private boolean hasPermission(HttpServletRequest request,String permission) {
        // 数据库中查询用户角色
        int roles = 1;
        // 在jwt中，可以从token中获取用户信息
        String authorization = request.getHeader("Authorization");
        if (!"ADMIN".equals(permission)){
             roles = 0;
        }
        if (authorization!= null && authorization.startsWith("Bearer ")) {
            token = authorization.substring(7);
            // 从token中解析用户信息并返回
            int role = (int) Objects.requireNonNull(JwtUtils.parseJwt(token)).get("role");
            return role == roles;
        } else {
            // 未登录，返回false
            return false;
        }
    }
}